package si.cir.gui;

import java.util.TreeMap;

import si.cir.R;
import si.cir.util.WSclient;
import android.app.ListFragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class AipsPredmetListFragment extends ListFragment {
	
	private TreeMap<String, String> predmeti;
	private String imePredmeta;
	
	private Runnable getNoviceBackgroundThread = new Runnable() {
		public void run() {
			getPredmetiInBackgroundThread();
		}
	};
	
	public AipsPredmetListFragment(String imePredmeta){
		this.imePredmeta = imePredmeta;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		setListShown(false);

		Thread thread = new Thread(null, getNoviceBackgroundThread, "Background");
		thread.start();
	}
	
	private void getPredmetiInBackgroundThread() {
		predmeti = WSclient.getPredmeti(imePredmeta);
		if(predmeti == null || predmeti.size() == 0){
			getActivity().runOnUiThread(new Runnable() {

				public void run() {
					Toast.makeText(getActivity(), "V tej kategoriji ni objav",
						Toast.LENGTH_LONG).show();
					getActivity().finish();
				}
			});
		}else if(predmeti.size() == 1){
			Intent intent = new Intent(getActivity(), AipsEndActivity.class);
			intent.putExtra("predmetId", predmeti.firstKey());
			startActivity(intent);
			getActivity().finish();
		}else{
			getActivity().runOnUiThread(new Runnable() {
				public void run() {
					setListAdapter(new ArrayAdapter<String>(getActivity(), R.layout.simple_item, predmeti.values().toArray(new String[]{})));
					setListShown(true);
				}
			});
		}
	}

	@Override
	public void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent intent = new Intent(getActivity(), AipsEndActivity.class);
		intent.putExtra("predmetId", (String)predmeti.keySet().toArray()[position]);
		startActivity(intent);
	}
}
